<template>
    <zt-dialog v-model="visible" :title="titleName" @confirm="confirmBtn" :loading="isLoading" :showFooter="true"
        :showFullScreen="false" width="600px" height="500px" :showConfirm="true">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" status-icon>
            <el-form-item label="目录名称" prop="catalogName">
                <el-input v-model.trim="ruleForm.catalogName" placeholder="请输入目录名称" clearable />
            </el-form-item>

            <el-form-item label="目录标识" prop="catalogSerial">
                <el-input v-model.trim="ruleForm.catalogSerial" placeholder="请输入目录标识" clearable> </el-input>
            </el-form-item>
            <el-form-item label="目录范围" prop="scope">
                <el-select v-model="ruleForm.scope" class="m-2" placeholder="请选择目录范围" style="width: 100%;" disabled
                    clearable>
                    <el-option v-for="item in menuTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="remark">
                <el-input v-model.number="ruleForm.remark" placeholder="请输入描述" type="textarea" />
            </el-form-item>

        </el-form>
    </zt-dialog>
</template>

<script setup>
import * as ElIcons from "@element-plus/icons-vue";
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { apiPostCreateDirectory, apiPutUpdateDirectory } from "@/api/admin/menuManage/api.js"
const isLoading = ref(false)
// 选中后的图标
const selectValue = ref('')

const emit = defineEmits(['success', 'update:modelValue'])
const props = defineProps({
    // 当前类型
    currentType: {
        type: String,
        default: 'add'
    },
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})

const ruleFormRef = ref(null)
const ruleForm = reactive({
    catalogName: '',//目录名称,
    catalogSerial: '',//目录标识
    remark: '',//目录描述
    scope: 'tenant',//目录范围(代码 0:master/1:tenant),可用值:master,tenant	
    shared: true,//公共目录(代码 true:公共/false:分配)
    builtin: false,//内置标识(Boolean false:非内置/true:内置)
})

const updateForm = reactive({
    catalogId: '',//菜单id
})
const menuTypeList = ref([
    {
        value: 'master',
        label: '系统'
    },
    {
        value: 'tenant',
        label: '租户'
    }])

const rules = reactive({
    catalogName: [
        { required: true, message: '请输入目录名称', trigger: 'blur' },
    ],
    catalogSerial: [
        { required: true, message: '请输入目录标识', trigger: 'blur' },
    ],
    scope: [
        {
            required: true,
            message: '请选择目录范围',
            trigger: 'change',
        },
    ],
})

// 动态获取标题
const titleName = computed(() => {
    return props.currentType == 'edit' ? '修改目录' : '添加目录'
})

// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        // 清除表单字段值
        Object.keys(ruleForm).forEach(key => {
            switch (key) {
                case 'scope':
                    ruleForm[key] = 'tenant'
                    break;
                default:
                    ruleForm[key] = '';
                    break;
            }
        });
        ruleFormRef.value.clearValidate()
        emit('update:modelValue', value)
    },
})

// 监听传递过来的值 赋值
watch(() => props.objectValue, (e) => {
    if (e) {
        if (props.currentType != 'add') {
            // 遍历 key 相等的赋值 
            Object.keys(e).forEach(item => {
                Object.keys(ruleForm).forEach(ele => {
                    if (item == ele) {
                        ruleForm[ele] = e[item]
                    }
                });
            });
        }
        updateForm.catalogId = e.catalogId
    }
}, {
    deep: true,
    immediate: true
})
// 确认按钮
async function confirmBtn() {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            // 编辑时执行
            if (props.currentType == 'edit') {
                editChange()
                return false
            }
            addChange()//添加

        } else {
            const firstValue = Object.values(fields)[0];
            ElMessage({
                message: firstValue[0].message,
                type: 'warning',
            })
        }
    })
}

// 添加方法
function addChange() {
    isLoading.value = true
    apiPostCreateDirectory({ ...ruleForm, parentId: props.objectValue.menuId }).then(res => {
        if (res.success) {
            ElMessage({
                message: '菜单添加成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

// 编辑方法
function editChange() {
    isLoading.value = true
    apiPutUpdateDirectory({ ...ruleForm, ...updateForm }).then(res => {
        if (res.success) {
            ElMessage({
                message: '菜单修改成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

const getIconData = () => {
    let icons = [];
    for (const name in ElIcons) {
        icons.push(name);
    }
    return icons;
};
const iconList = reactive({
    icons: getIconData(),
});

const popoverRef = ref(null)
// 图标选择
const handleIconChange = (value) => {
    selectValue.value = value
    ruleForm.iconCls = value
    popoverRef.value.hide()
}



</script>

<style lang='scss' scoped>
.icon-list {
    .item-icon {
        &:hover {
            color: #333;
        }
    }
}
</style>